package com.saumya.robotlegs.controller
{
	import com.saumya.robotlegs.events.FileSearchEvent;
	import com.saumya.robotlegs.events.JSFLCreationEvent;
	import com.saumya.robotlegs.events.LoggerEvent;
	import com.saumya.robotlegs.model.JsflModel;
	import com.saumya.robotlegs.model.SearchedFilesModel;
	import com.saumya.utils.FileSearchUtil;
	
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import nl.demonsters.debugger.MonsterDebugger;
	
	import org.robotlegs.mvcs.Command;

	public class BeginFileSearchCommand extends Command
	{
		[Inject]
		public var evt:FileSearchEvent;
		
		[Inject]
		public var searchedFilesModel:SearchedFilesModel;
		
		[Inject]
		public var jsflModel:JsflModel;
		
		private var fileSearchUtil:FileSearchUtil;
		
		public function BeginFileSearchCommand()
		{
			//Does nothing
		}
		
		public override function execute():void
		{
			MonsterDebugger.trace(this,this.evt.getFileType());
			this.fileSearchUtil=new FileSearchUtil(this.evt.getFileType());
			//event listeners for the search utility
			this.fileSearchUtil.addEventListener(LoggerEvent.UPDATE_LOG,onUpdateLogMsg);
			this.fileSearchUtil.addEventListener(FileSearchUtil.SEARCH_COMPLETE, onSearchComplete);
			//finally calling the utility methods
			this.fileSearchUtil.searchInFolder(this.evt.getFileReference());
		}
		
		private function onSearchComplete(e:Event):void
		{
			var fsu:FileSearchUtil=FileSearchUtil(e.target);
			//MonsterDebugger.trace(this,fsu.getMeFiles().length);
			var allFiles:Array=fsu.getMeFiles();
			var allFolders:Array=fsu.getMeFolders();
			var fileTypeSearched:String=fsu.getFileTypeSearched();
			//calls model to store the data
			this.searchedFilesModel.clearAllData();
			this.searchedFilesModel.setFileType(fileTypeSearched);
			//
			var logEventOne:LoggerEvent=new LoggerEvent(LoggerEvent.UPDATE_LOG);
			logEventOne.setHilightOption(true);
			var logEventOneMsg:String='Search is Complete for Part1 : Begin Part2 : '+'\n';
			logEventOne.setLogMessage(logEventOneMsg);
			this.dispatch(logEventOne);
			//
			if (fileTypeSearched!='fla')
			{
				//log('Search Complete',true);
			}else {
				//pushing in folders
				for (var i:uint = 0; i < allFolders.length; i++)
				{
					var folder:File = allFolders[i];
					this.searchedFilesModel.addFolder(folder);
				}
				//-----------------------------FILES--------------------------------------
				//pushing in files
				for (var j:uint = 0; j < allFiles.length; j++ )
				{
					var fl:File = allFiles[j];
					this.searchedFilesModel.addFile(fl);
					//updating the user
					var logevt:LoggerEvent=new LoggerEvent(LoggerEvent.UPDATE_LOG);
					//msg
					var logmsg:String='num='+j+':: fileName=' + fl.name+' :: path='+fl.nativePath+'\n';
					logmsg+='path url = '+fl.url;
					//dispatch event
					logevt.setLogMessage(logmsg);
					this.dispatch(logevt);
				}
				//
				//this.makeJSFL();
			}
			
			//log this, so that users know its completed searching
			var le:LoggerEvent=new LoggerEvent(LoggerEvent.UPDATE_LOG);
			le.setHilightOption(true);
			var logMsg:String='Search is Complete : '+'\n';
			logMsg+='Searched for files of type : '+fileTypeSearched+'\n';
			logMsg+='Total files='+allFiles.length+' : folders='+allFolders.length;
			le.setLogMessage(logMsg);
			this.dispatch(le);
			//makes the JSFL script
			this.makeMasterJSFL();
		}
		
		//This is called when the utility dispatches the same event
		private function onUpdateLogMsg(e:LoggerEvent):void
		{
			//MonsterDebugger.trace(this,'new looger event');
			this.dispatch(e);
		}
//--------------------------------utility methods-----------------------------------------------------
		//Makes the master jsfl file
		private function makeMasterJSFL():void
		{
			//this.log('Making JSFL file now');
			var desktop:File = new File();
			desktop = File.desktopDirectory;
			var jsflFile:File = new File(desktop.url + '/temp.jsfl');
			//push the required data
			var jsData:String = '';
			var allFiles:Array=this.searchedFilesModel.getAllFiles();
			for (var i:uint = 0; i < allFiles.length;i++ )
			{
				var fileURI:String = File(allFiles[i]).url;
				
				jsData += "var fileURI='"+fileURI+"';" + '\n';
				jsData += "fl.publishDocument(fileURI);" + '\n';
			}
			//save the file
			var mainJSFLCreated:Boolean = this.saveJSFL('mainJSFL', jsData,true);
			
			if (mainJSFLCreated)
			{
				MonsterDebugger.trace(this,'Master JSFL : CREATED SUCCESSFULLY.');
				var jsflEvent:JSFLCreationEvent=new JSFLCreationEvent(JSFLCreationEvent.MASTER_CREATION);
				this.dispatch(jsflEvent);
			}else {
				MonsterDebugger.trace(this,'Master JSFL : CREATION FAILED!!');
			}
			
		}
		
		private function saveJSFL(fileNameString:String='default',fileContent:String='nothing',isMasterFile:Boolean=false):Boolean
		{
			var fileName:String = fileNameString;
			var content:String = fileContent;
			
			var masterJSFL:File=new File();
			
			var myPattern:RegExp = / /g;
			var newFileName:String = fileName.replace('.txt','');
			if(newFileName.length > 1){
				var file:File = File.desktopDirectory.resolvePath("buildFiles/" + newFileName.replace(myPattern, '_') + ".jsfl");
				//saving the file preferences
				if (isMasterFile)
				{
					masterJSFL = file;
					this.jsflModel.setMasterScriptFile(file);
				}else {
					//this.jsflFiles.push(file);
					//Else does Nothing
				}
				//moving ahead with creation of the file
				var stream:FileStream = new FileStream();
				stream.open(file, FileMode.WRITE);
				var str:String = content;
				//str = str.replace(/\r/g, File.lineEnding);
				stream.writeUTFBytes(str);
				stream.close();
			} else {
				return false;
			}
			return true;
		}
	}
}